package com.younge.spring.service;

import com.younge.spring.api.common.PageResult;
import com.younge.spring.api.param.UserAddParam;
import com.younge.spring.api.param.UserListParam;
import com.younge.spring.repository.SysUserRepository;
import com.younge.spring.repository.dao.Demo;
import com.younge.spring.repository.dao.SysUser;
import jakarta.persistence.criteria.Predicate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserService {
    private final SysUserRepository sysUserRepository;

    public SysUserService(SysUserRepository sysUserRepository) {
        this.sysUserRepository = sysUserRepository;
    }

    public String addUser(UserAddParam userAddParam) {
//        SysUser sysUser = new SysUser();
//        sysUser.setUsername(userAddParam.getUsername());
//        sysUser.setPassword(userAddParam.getPassword());
//        sysUserRepository.save(sysUser);
        return "用户创建成功！";

    }

    public Page<SysUser> getUserList(UserListParam userListParam) {
        Pageable pageable = PageRequest.of(userListParam.getPage() - 1, userListParam.getPageSize());
        Specification<SysUser> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            String username = userListParam.getUsername();
            if (username != null && !username.isBlank()) {
                predicates.add(cb.equal(root.get("username"), username));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return sysUserRepository.findAll(spec, pageable);
    }
}